<template>
  <el-upload :action="action" :headers="headers" :http-request="uploadFile">
    <template v-for="(item, key, index) in $slots" :key="index" #[key]>
      <slot :name="key" />
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import type { UploadRequestHandler, UploadRequestOptions } from "element-plus";
import { ajaxUpload } from "@/utils/fileajax";
import FileHashUtil from "@/utils/file_hash_util";

import { fileApi } from "@/api/file";
// 上传文件的地址
const action = ref(fileApi.uploadUrl());
// 请求上传的头部
const headers = ref(fileApi.authHeader());

//自定义文件上传
const uploadFile: UploadRequestHandler = (
  option: UploadRequestOptions
): XMLHttpRequest | Promise<any> => {
  const fileHashUtil = new FileHashUtil();
  return new Promise((resolve) => {
    //console.log(option);
    fileHashUtil.hash(option.file).then((hash: string[]) => {
      //console.log(hash);
      fileApi
        .existFileHex(option.file, hash[0], hash[1])
        .then((res) => {
          if (res.status === 404) {
            resolve(ajaxUpload(option));
          } else {
            //console.log(res.data);
            resolve(res.data);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    });
  });
};
</script>
